<?php
/**
 *
 * 版权所有：恰维网络<qwadmin.qiawei.com>
 * 作    者：寒川<hanchuan@qiawei.com>
 * 日    期：2015-09-17
 * 版    本：1.0.0
 * 功能说明：后台公用控制器。
 *
 **/

namespace Qwadmin\Controller;

use Common\Controller\BaseController;
use Think\Auth;

class ComController extends BaseController
{
    public $USER;
    protected $_row = 20;
    //不需要权限认证的方法
    private $_no_checked_method = array(
        'menu' => ',update,',
        'logout' => ',index,',
        'personal' => ',profile,',
        'setting' => ',setting,',
        'login' => '*',
        'index' => ',index,',
        'group' => ',update,',
        'cache' => ',clear,'
    );
    public function _initialize()
    {
        C(setting());
        if (!C("COOKIE_SALT")) {
            $this->error('请配置COOKIE_SALT信息');
        }
        /**
         * 不需要登录控制器
         */
        if (in_array(CONTROLLER_NAME, array("Login"))) {
            return true;
        }
        //检测是否登录
        $flag =  $this->check_login();
        $url = U("login/index");
        if (!$flag) {
            header("Location: {$url}");
            exit(0);
        }
        $UID = $this->USER['uid'];
        $user = member(intval($UID));
        $this->assign('user', $user);
        
        /**
         * 不需要登录控制器
         */
        $auth_menus_list = $this->_checkedAuth( $UID );
        if( $auth_menus_list === false && ( !isset( $this->_no_checked_method[ strtolower( CONTROLLER_NAME ) ] ) || ( $this->_no_checked_method[ strtolower( CONTROLLER_NAME ) ] == '*' && strpos($this->_no_checked_method[ strtolower( CONTROLLER_NAME ) ] , ','.strtolower(ACTION_NAME).',') !== false ) ) ) {
            $this->error( '非常抱歉，您没有权限访问！' );
        }
        $this->assign( 'auth_lists' , $auth_menus_list );
        $menu_default_data = $this->_defaultMenu();
        $this->assign('default_menu' , $menu_default_data);
        //初始化默认左边菜单
		if( $menu_default_data['menus_id'] ) {
			$menus_id = $menu_default_data['menus_id'];
		} else {
			$menus_datas = current( $auth_menus_list );
			$menus_id = $auth_menus_list[0]['id'];
		}
		$restart_menu_list = array();
		foreach( $auth_menus_list as $key => $value ) {
			$restart_menu_list[$value['id']] = $value;
		}
        $this->assign( 'auth_default_data' , $restart_menu_list[$menus_id]['list'] );
		//城市选择
		$areaList = M('area')->where(array('parent_id'=>0))->select();
		$area = array();
		
		foreach($areaList as $key=>$val){
			$a =  M('area')->where(array('parent_id'=>$val['id']))->select();
			$area[0][$val['id']] = $val['name'];
			foreach($a as $ke=>$va){
				$b =  M('area')->where(array('parent_id'=>$va['id']))->select();
				$area[$val['id']][$va['id']] = $va['name'];
				foreach($b as $k=>$v){
						$area[$va['id']][$v['id']] = $v['name'];
				}
			}
		}
		$this->assign('area', json_encode($area));
		//城市end
    }
	
	protected function getMenu($items, $id = 'id', $pid = 'pid', $son = 'children')
    {
        $tree = array();
        $tmpMap = array();

        foreach ($items as $item) {
            $tmpMap[$item[$id]] = $item;
        }

        foreach ($items as $item) {
            if (isset($tmpMap[$item[$pid]])) {
                $tmpMap[$item[$pid]][$son][] = &$tmpMap[$item[$id]];
            } else {
                $tree[] = &$tmpMap[$item[$id]];
            }
        }
        return $tree;
    }
	
    public function check_login(){
        session_start();
        $flag = false;
        $salt = C("COOKIE_SALT");
        $ip = get_client_ip();
        $ua = $_SERVER['HTTP_USER_AGENT'];
        $auth = cookie('auth');
        $uid = session('uid');
        if ($uid) {
            $user = M('member')->where(array('uid' => $uid))->find();

            if ($user) {
                if ($auth ==  password($uid.$user['user'].$ip.$ua.$salt)) {
                    $flag = true;
                    $this->USER = $user;
                }
            }
        }
        return $flag;
    }
    
    
    /**
     * 分页信息
     * @param int $total 数据总数
     */
    protected function __assignPage( $total ) {
        if( $total > $this->_row ) {
            $page_gen = new \Think\Page( $total , $this->_row );
            $this->assign( 'page' , $page_gen->show() );
        }
        $this->assign('count' , $total );
        $this->assign('nowPage' , I('get.p') ? I('get.p') : 1 );
    }
    
    // ======================== 新权限操作 =========================
    /**
     * 新权限列表读取
     * @param type $name Description
     */
    protected function __redayNewMenusAuthList( $type = 1) {
        if( $type == 1 ) {
            $menus_data = M('Menus')->order('sort DESC')->select();
            foreach( $menus_data as $key => $value ) {
                $actions_data = M('Actions')->where(array('menus_id' => $value['id']))->order('sort DESC')->select();
                if( $actions_data ) {
                    foreach( $actions_data as $k => $v ) {
                        $method_data = M('Methods')->where(array('actions_id' => $v['id'],'parent_id' => 0))->order('sort DESC')->select();
                        foreach( $method_data as $_k => $_v ) {
                            $method_data[$_k]['urls'] = U( $_v['url'] );
                            $method_data[$_k]['list'] = M('Methods')->where(array('parent_id' => $_v['id']))->select();
                        }
                        $actions_data[$k]['list'] = $method_data;
                    }
                    $menus_data[$key]['list'] = $actions_data;
                }
            }
            return $menus_data;
        } else {
            return array(M('Menus')->index('id')->order('sort DESC')->select() , M('Actions')->index('id')->order('sort DESC')->select() , M('Methods')->index('id')->order('sort DESC')->select());
        }
    }

    /**
     * 验证用户是否有权限访问
     */
    private function _checkedAuth( $admin_id ) {
        $group_data = M('auth_group_access')->alias('aga')->join('__AUTH_GROUP__ ag ON ag.id = aga.group_id')->field('ag.*')->where( array( 'aga.uid' => $admin_id , 'ag.status' => 1 ) )->order('aga.group_id ASC')->select();
		//如果不是超级管理组，则获得用户的权限
        if( $group_data[0]['id'] == 1 ) {
            return $this->__redayNewMenusAuthList();
        }
        //用户所在的管理组权限合并
        $auth_list = array();
        foreach( $group_data as $key => $value ) {
            $auth_list = array_merge( $auth_list , explode(',' , $value['auth_list'] ) );
        }
        //去掉重复数据
        $auth_list = array_unique( $auth_list );
        $method_data = M('Methods')->where( array( 'url' => CONTROLLER_NAME . '/'. ACTION_NAME ) )->find();
        //if( !$method_data ) return false;
        $auth_list = implode(',' , $auth_list);
        //比对是否存在
        if( strpos( $auth_list , $method_data['id'] . '=' . $method_data['url'] ) === false ) {
            return false;
        }
        //去掉只用来验证的数据留下ID
        $auth_list = preg_replace( '/(=[A-Za-z0-9]+\/[A-Za-z0-9]+(,)?)/is' , '$2' , $auth_list );
        //转换为二维数组
        $auth_list = explode(',' , $auth_list);
        foreach( $auth_list as $key => $value ) {
            $auth_list[$key] = explode( '|' , $value );
        }
        //获得所有菜单按钮
        $auth_menus = $this->__redayNewMenusAuthList( 2 ); 
        //获得专属于用户权限的菜单栏
        $new_auth_list = array();
        foreach( $auth_list as $key => $value ) {
            !$new_auth_list[$value[0]] ? $new_auth_list[$value[0]] = $auth_menus[0][$value[0]] : '';
            !$new_auth_list[$value[0]]['list'][$value[1]] ? $new_auth_list[$value[0]]['list'][$value[1]] = $auth_menus[1][$value[1]] : '';
            if( $auth_menus[2][$value[2]]['parent_id'] <= 0 ) {
                $method_datas = $auth_menus[2][$value[2]];
                $method_datas['urls'] = U($method_datas['url']);
                $new_auth_list[$value[0]]['list'][$value[1]]['list'][$value[2]] = $method_datas;
            }
        }
        $new_auth_list = array_reverse( $new_auth_list );
        return $new_auth_list;
    }
    
    /**
     * 获得点击按钮的默认数据ID
     */
    private function _defaultMenu() {
        $data = M('Methods')->alias('m')->join('__ACTIONS__ a ON a.id = m.actions_id')->join('__MENUS__ ms ON ms.id = a.menus_id')->where(array( 'url' => CONTROLLER_NAME . '/'. ACTION_NAME ))
                            ->field('ms.id AS menus_id,a.id AS actions_id')->find();
        $methods = M('Methods')->alias('m')->join('LEFT JOIN __METHODS__ ms ON ms.id = m.parent_id')->where(array( 'm.url' => CONTROLLER_NAME . '/'. ACTION_NAME ))->field('m.id,ms.id AS id1')->find();
        $data['methods_id'] = $methods['id1'] ? $methods['id1'] : $methods['id'];
        return $data;
    }
}